<template>
  <div v-if="historyData.length > 0" class="price-history-display">
    <el-row :gutter="20">
      <!-- 三块报价历史，复用同一个组件逻辑 -->
      <el-col v-for="quoteNum in [1, 2, 3]" :key="quoteNum" :span="8">
        <div class="history-card">
          <!-- 卡片标题 -->
          <div class="card-header">
            <span class="card-title">报价{{ quoteNum }}</span>
          </div>

          <!-- 变更记录列表 -->
          <div class="change-list">
            <template v-if="getQuoteChanges(quoteNum).length > 0">
              <div
                v-for="(change, index) in getQuoteChanges(quoteNum)"
                :key="index"
                class="change-record"
              >
                <!-- 一行显示变更信息 -->
                <div class="record-line">
                  <UserLabel :model-value="change.createId" />
                  在{{ formatDateTime(change.createTime) }}修改{{ getChangeText(change.items) }}
                </div>
              </div>
            </template>

            <!-- 无记录时的显示 -->
            <div v-else class="no-records">暂无报价{{ quoteNum }}变更记录</div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { formatDateTime } from "@/utils/date.js";

defineOptions({
  name: "PriceHistoryDisplay",
});

const props = defineProps({
  historyData: {
    type: Array,
    default: () => [],
  },
});

// 获取指定报价的变更记录
function getQuoteChanges(quoteNumber) {
  if (!props.historyData.length) return [];

  // 按时间排序（最新的在前）
  const sortedHistory = [...props.historyData].sort(
    (a, b) => new Date(b.createTime) - new Date(a.createTime)
  );

  const changes = [];

  // 处理每条记录，比较与前一条的变化
  for (let i = 0; i < sortedHistory.length; i++) {
    const current = sortedHistory[i];
    const previous = sortedHistory[i + 1]; // 前一条记录（时间更早）

    const priceField = `price${quoteNumber}`;
    const weightField = `weight${quoteNumber}`;

    const currentPrice = current[priceField];
    const currentWeight = current[weightField];
    const previousPrice = previous ? previous[priceField] : null;
    const previousWeight = previous ? previous[weightField] : null;

    // 检查是否有变化
    const priceChanged = currentPrice !== previousPrice;
    const weightChanged = currentWeight !== previousWeight;

    // 如果有任何变化，记录这次变更
    if (priceChanged || weightChanged) {
      const changeItems = [];

      if (priceChanged) {
        changeItems.push({
          type: "price",
          label: "价格",
          oldValue: previousPrice,
          newValue: currentPrice,
          unit: "元",
        });
      }

      if (weightChanged) {
        // 判断是否为无意义的重量值（null、undefined、0）
        const isInvalidWeight = (weight) => weight == null || weight === 0;

        // 如果从无意义值变为无意义值，不展示此变更
        const isInvalidChange = isInvalidWeight(previousWeight) && isInvalidWeight(currentWeight);

        if (!isInvalidChange) {
          changeItems.push({
            type: "weight",
            label: "重量",
            oldValue: previousWeight,
            newValue: currentWeight,
            unit: "kg",
          });
        }
      }

      // 只有当有有效的变更项时，才添加到变更记录中
      if (changeItems.length > 0) {
        changes.push({
          createId: current.createId,
          createTime: current.createTime,
          items: changeItems,
        });
      }
    }
  }

  return changes;
}

// 生成变更文本
function getChangeText(items) {
  return items
    .map((item) => {
      return `${item.label}${item.oldValue || "无"}→${item.newValue}${item.unit}`;
    })
    .join("，");
}
</script>

<style scoped>
.price-history-display {
  width: 100%;
}

.history-card {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  /* height: 200px; */
  display: flex;
  flex-direction: column;
}

.card-header {
  background-color: #f5f7fa;
  padding: 0px 12px;
  border-bottom: 1px solid #ebeef5;
  border-radius: 4px 4px 0 0;
}

.card-title {
  font-size: 13px;
  font-weight: 500;
  color: #303133;
}

.change-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.change-record {
  padding: 4px 0;
  border-bottom: 1px solid #f0f0f0;
}

.change-record:last-child {
  border-bottom: none;
}

.record-line {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
  display: flex;
  align-items: center;
  gap: 4px;
}

.no-records {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
}
</style>
